﻿using CommunityToolkit.Mvvm.Input;
using HandyControl.Data;
using Koala.Pro.Common;
using Koala.Pro.Common.Extension;
using Koala.Pro.Helpers;
using Koala.Pro.ViewModels;
using System.Windows;
using System.Windows.Input;
using Wpf.Ui.Controls;

namespace Koala.Pro.Views.Pages
{
    public partial class DataEntityPage : Window, INavigableView<DataEntityViewModel>
    {
        public DataEntityViewModel ViewModel { get; }

        public DataEntityPage(DataEntityViewModel viewModel)
        {
            ViewModel = viewModel;
            base.DataContext = this;
            InitializeComponent();
            ViewModel.GetTree();
        }

        private async void tree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (e.NewValue is CustomTreeNode selectNode)
            {
                ViewModel.TreeModel.SelectNode = selectNode;
            }
        }

        private void SearchBar_OnSearchStarted(object sender, FunctionEventArgs<string> e)
        {
            ViewModel.TreeModel.SearchKey = e.Info;
            if (e.Info.IsNullOrEmpty())
            {
                ViewModel.TreeModel.FilteredTreeItems = ViewModel.TreeModel.TreeItems;
                return;
            }
            ViewModel.TreeModel.FilteredTreeItems = ViewModel.TreeModel.TreeItems.FindCustomNodes((CustomTreeNode s) => s.Name.Contains(e.Info, StringComparison.OrdinalIgnoreCase));
        }

        private async void tree_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (tree.SelectedItem is CustomTreeNode customTreeNode)
            {
                customTreeNode.IsChecked = true;
                Confirm();
            }
        }

        [RelayCommand]
        private void OpenSysAssembly()
        {
            ViewModel.FilePathName = "";
            ViewModel.GetTree();
        }

        [RelayCommand]
        private void OpenOtherAssembly()
        {
            ViewModel.LoadFile();
        }

        [RelayCommand]
        private void Back()
        {
            Close();
        }

        [RelayCommand]
        private void Confirm()
        {
            ViewModel.Confirm();
            List<string> checkedList = ViewModel.CheckedList;
            if (checkedList != null && checkedList.Count > 0)
            {
                base.DialogResult = true;
            }
            else
            {
                MessageDxUtil.ShowTips("请选择至少一条记录");
            }
        }
    }
}
